#include <Servo.h> //Use the Servo librarey for generating PWM
Servo ESC; //name the servo object, here ESC
String throttle;
const int buzzer = 2;     // the number of the buzzer  pin
const int ledPin =  4;      // the number of the LED pin

void setup()
{
ESC.attach(9); //Generate PWM in pin 9 of Arduino
Serial.begin(9600);
ESC.write(0);
  pinMode(ledPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buzzer, OUTPUT);
}

void loop()
{
  if(Serial.available()>0){
 throttle  = Serial.readString();
  if(throttle=="start")    
  {
  Serial.println(" Start,  ready go!"); //开始启动程序
     while(1)
     {
    throttle  = Serial.readString();
     
     if(throttle=="stop")                     //暂停，速度减为零
     {  
     Serial.println(" Stop"); 
     ESC.write(0);
   ESC.writeMicroseconds(1000);
     }

     else if(throttle=="one")                 //调节滑板速度为1
     {  
     Serial.println(" speed 1"); 
     ESC.writeMicroseconds(1300);
     }
     
     else if(throttle=="two")                 //调节滑板速度为2
     {  
     Serial.println(" speed 2"); 
     for(int i=1300;i<=1450;i++)
      {
     ESC.writeMicroseconds(i);
     delay(10);
     }
     }
     
     else if(throttle=="three")                 //调节滑板速度为3
     {  
     Serial.println(" speed 3"); 
     for(int i=1450;i<=1600;i++)
      {
     ESC.writeMicroseconds(i);
     delay(10);
     }
     }
     
    else if(throttle=="four")                 //调节滑板速度为4
     {  
     Serial.println(" speed 4"); 
     for(int i=1600;i<=1800;i++)
      {
     ESC.writeMicroseconds(i);
     delay(10);
     }
     }
     
     else if(throttle=="turn on")                 //点亮前灯
     {  
      digitalWrite(ledPin, HIGH);
      Serial.println(" turn on"); 
     }
     
      else if(throttle=="turn off")                 //熄灭前灯
     {  
     digitalWrite(ledPin, LOW);
     Serial.println(" turn off"); 
     }

      else if(throttle=="buzzer on")                 //铃铛响
     {  
      int times=6;
      Serial.println(" buzzer on"); 
      for(int i=0;i<=times;i++)
      {
     digitalWrite(buzzer, HIGH);
     delay(500);
     digitalWrite(buzzer, LOW);
     delay(300);
     }
     }
     
      else if(throttle=="buzzer off")                 //铃铛不响
     {  
     digitalWrite(buzzer, LOW);
     Serial.println(" buzzer off"); 
     }
     
    else if(throttle=="reset")                 //重新启动
     {  
     Serial.println(" Reset"); 
     digitalWrite(buzzer, LOW);
     digitalWrite(ledPin, LOW);
     ESC.writeMicroseconds(1000);
     break;
     }
     }
     }
delay(4000);
Serial.println(" waiting...");
}
}
